package calcul;

import java.util.ArrayList;
public class MascTransform {
/**
 * 
 * @param arr ArrayList to be completed with the specified numbers
 * @param num numbers to be inserted into ArrayList
 * @param cuantity 
 */
	private void fillArrListNumbers(ArrayList<Integer> arr, int num,
			int cuantity) {
		for (int i = 0; i < cuantity; i++) {
			arr.add(num);
		}
	}
/**
 * 
 * @param shortMask mask in short form 1 - 32
 * @return masc in long form
 * @throws Exception 
 */
	public ArrayList<Integer> shortToLong(ArrayList<Integer> shortMask) throws Exception {
		int numOfUni;
		String boolNum = new String();
		ArrayList<Integer> arr = new ArrayList();

		/** insert full octet */
		fillArrListNumbers(arr, 255, shortMask.get(0) / 8);

		numOfUni = shortMask.get(0) - 8 * (shortMask.get(0) / 8);
		
		/** controls whether mask them correctly defined */
		boolean flag = false;
		for (int i = 0; i < 8; i++) {
			if (i < numOfUni) {
				if(flag){
					throw new Exception("invalid mac adress");
				}
				boolNum += "1";
			} else {
				flag = true;
				boolNum += "0";
			}
		}
		arr.add(Integer.parseInt(boolNum, 2));
		fillArrListNumbers(arr, 0, 4 - shortMask.get(0) / 8 - 1);
		return arr;
	}

	/**
	 * 
	 * @param masc
	 *            arrayList with 4 int numbers between 0 - 255
	 * @return short form of the mask 0 - 32
	 * @throws Exception
	 *             if mask is not correctly specified
	 */
	public ArrayList<Integer> longToShort(ArrayList<Integer> masc) throws Exception {
		int i = 0;
		boolean firstZero = false;
		ArrayList<Integer> rsp = new ArrayList<>();
		for (Integer macNumber : masc) {

			String binaryTemp = Integer.toBinaryString(macNumber);
			for (char ch : binaryTemp.toCharArray()) {
				if (ch == '1' && !firstZero) {
					i++;
					continue;
				} else if (ch == '0' && !firstZero) {
					firstZero = true;
				} else if (ch == '1' && firstZero) {
					throw new Exception("invalid mac adress");
				}
			}
		}
		rsp.add(i);
		return rsp;
	}
}
